package net.zhangyun;

import net.zhangyun.utils.MyConsole;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;

public class ReactiveClient {

    private static Scheduler scheduler = Schedulers.boundedElastic();
    private static WebClient client = WebClient.create("http://localhost:8080");

    public static void main(String[] args) throws InterruptedException {
        getSample();
        postSample();
    }

    private static void getSample() throws InterruptedException {
        client.get()
                .uri("/pets")
                .retrieve()
                .bodyToMono(String.class)
                .publishOn(scheduler)
                .subscribe(
                        MyConsole::printSingle,
                        MyConsole::printMessage
                );

        // Prevent main thread's death before the print
        Thread.sleep(2000);
    }

    private static void postSample() throws InterruptedException {
        client.post()
                .uri("/pets")
                .body(BodyInserters.fromPublisher(Mono.just("{\"type\":\"Animal\",\"name\":\"Alien\"}"), String.class))
                .retrieve()
                .bodyToMono(String.class)
                .publishOn(scheduler)
                .subscribe(
                        MyConsole::printSingle,
                        MyConsole::printMessage
                );

//        Mono.just("{\"type\":\"Animal\",\"name\":\"Alien\"}").flatMap(body ->
//            client.post()
//                    .uri("/pets")
//                    .body(BodyInserters.fromValue(body))
//                    .retrieve()
//                    .bodyToMono(String.class)
//        ).publishOn(scheduler).subscribe(
//                MyConsole::printSingle,
//                MyConsole::printMessage
//        );

        // Prevent main thread's death before the print
        Thread.sleep(2000);
    }
}
